package com.zian.Interceptor;

import cn.hutool.core.util.StrUtil;
import com.zian.common.CommonConstant;
import com.zian.context.BaseContext;
import com.zian.domain.po.SysAdminUser;
import com.zian.domain.po.SysUser;
import com.zian.exception.LoginException;
import com.zian.properties.JwtProperties;
import com.zian.service.ITokenService;
import com.zian.utils.JwtUtil;
import com.zian.utils.RedisUtils;
import io.jsonwebtoken.Claims;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.Serializable;
import java.util.Date;
import java.util.concurrent.TimeUnit;

@Slf4j
@Component
@RequiredArgsConstructor
public class UserAuthInterceptor implements HandlerInterceptor {

    private final ITokenService tokenService;

    /**
     * 进入控制层之前 , 对一些请求做拦截处理 ， 校验 token
     *
     * @param request
     * @param response
     * @param handler
     * @return 返回的 布尔值 false 代表拦截  true 代表放行
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String uri = request.getRequestURI();
        log.info("进入 [ UserAuthInterceptor ] 拦截器 , 拦击到：uri：{}", uri);
        //判断当前拦截到的是Controller的方法还是其他资源
        if (!(handler instanceof HandlerMethod)) {
            //当前拦截到的不是动态方法，直接放行
            return true;
        }

        Long userId = tokenService.parseToken(request, false);
        // 设置当前线程的 userId
        BaseContext.setCurrentId(userId);

        return true;

    }
}
